package pure.csw.activemq.topicFeatureTest;

import org.apache.activemq.ActiveMQConnectionFactory;
import pure.csw.common.Constant;

import javax.jms.*;
import java.io.IOException;

public class TopicSubscriber {
    public static void main(String[] args) throws JMSException, IOException {
        //注册工厂，开启连接
        ActiveMQConnectionFactory factory = new ActiveMQConnectionFactory(Constant.URL);
        Connection connection = factory.createConnection();
        connection.start();
        //获取一次会话
        Session session = connection.createSession(false, Session.AUTO_ACKNOWLEDGE);
        Topic topic = session.createTopic(Constant.TOPICNAME);
        MessageConsumer consumer = session.createConsumer(topic);
        //设置消息监听器
        consumer.setMessageListener(new MessageListener() {
            @Override
            public void onMessage(Message message) {
                if (message != null && message instanceof TextMessage) {
                    TextMessage textMessage = (TextMessage)message;
                    try {
                        System.out.println(textMessage.getText());
                    } catch (JMSException e) {
                        e.printStackTrace();
                    }
                }
            }
        });
        //保证消息监听器的运行
        System.in.read();
        consumer.close();
        session.close();
        connection.close();
    }
}
